var requestFriend = function(id, targetId, options){
	this.id = id;
	this.targetId = targetId;
	this.success = (typeof options.success == 'function')? options.success : new Function();
	this.error = (typeof options.error == 'function')? options.error : new Function();
	this.request();
};
requestFriend.prototype = {
	request: function(){
		var self = this;
		if(this.id == this.targetId) {
			self.error(9999, 'Can not request your self');
			throw new Exception(9999, 'Can not request your self');
		}
		var id1 = Mysql.escape(this.id);
		var id2 = Mysql.escape(this.targetId);
		this.checkUser(this.targetId, function(){
			Mysql.query("SELECT count(id) FROM Friend WHERE (userId1="+id1+" AND userId2="+id2+") OR (userId1="+id2+" AND userId2="+id1+")").on('error', function(error){
				console.log('mysql error: '+error);
				self.error(9999, 'mysql error');
				throw new Exception(9999, 'mysql error');
			}).on('result', function(result){
				if(result['count(id)'] != 0) {
					self.error(9999, 'Duplicate request friend');
					throw new Exception(9999, 'Duplicate request friend');
				}
				Mysql.query("INSERT INTO Friend(userId1,userId2,areFriend) VALUES("+id1+","+id2+",1)").on('error', function(error){
					self.error(9999, 'mysql error');
					throw new Exception(9999, 'mysql error');
				}).on('result', function(result){
					self.success(result);
					return;
				});
			});
		});
	},
	checkUser: function(targetId, success){
		var self = this;
		Mysql.query("SELECT count(id) FROM Account WHERE id="+Mysql.escape(targetId)).on('error', function(error){
			console.log('mysql error: '+error);
			self.error(9999, 'mysql error');
			throw new Exception(9999, 'mysql error');
		}).on('result', function(result){
			console.log(result);
			if(result['count(id)'] == 0) {
				self.error(9999, 'Not found user');
				throw new Exception(9999, 'Not found user');
			}
			success();
		});
	}
};
module.exports = requestFriend;